//
//  SEGShowPhotoView.m
//  Uhomebk
//
//  Created by wangmingmin on 2017/10/25.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "SEGShowPhotoView.h"
@interface SEGShowPhotoView () <UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *imgScrollView;
@property (nonatomic, strong) NSMutableArray *imageArray;//url
@property (strong, nonatomic)UIPageControl * pageControl;
@property (nonatomic, strong) NSMutableArray <UIImage *>*imagePictureArr;//图片
@end

@implementation SEGShowPhotoView
{
    NSMutableArray <UIImage *>* imagesChangeArray;//用于返回数据，比如删除图片等操作后获取新的图片数据等
    NSInteger pageNumber;//当前页,默认为0,首先展示第一张,可更改
    UITapGestureRecognizer *tap;
    UIView * viewNavItem;
    NSInteger selectIndex;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self creatBackButton];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)setTitle:(NSString *)title
{
    UILabel *titleLabel= [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
    titleLabel.font = kFont(16);
    titleLabel.textColor =  OSWhiteColor;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = title;
    self.navigationItem.titleView = titleLabel;
}

//导航栏左侧显示返回按钮
- (void)creatBackButton
{
    UIImage *image = [UIImage imageNamed:@"navBackNor_White"];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [leftButton setImage:image forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(onNavigationLeftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    
    leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, -25,0, 0);
    negativeSpacer.width = -10;
    self.navigationItem.leftBarButtonItems = @[negativeSpacer, leftButtonItem];
}

//导航栏右侧显示文字按钮
- (void)createNavigationRightFirstTextButtonWith:(NSString *)title selecteTitle:(NSString *)selectedTitle
{
    UILabel *tempLael = [[UILabel alloc] init];
    [tempLael setText:title];
    [tempLael sizeToFit];
    
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tempLael.bounds), 40)];
    [rightButton addTarget:self action:@selector(onNavigationRightFirstButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    rightButton.titleLabel.font = kFont(13);
    [rightButton setTitle:title forState:UIControlStateNormal];
    [rightButton setTitle:selectedTitle forState:UIControlStateSelected];
    [rightButton setTitleColor:OSWhiteColor forState:UIControlStateNormal];
    [rightButton setTitleColor:OSColor_Line forState:UIControlStateDisabled];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    rightButtonItem.tag = 111;
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    self.navigationItem.rightBarButtonItems = @[negativeSpacer, rightButtonItem];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *barApp = [UINavigationBarAppearance new];
        barApp.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
        self.navigationController.navigationBar.scrollEdgeAppearance = barApp;
        self.navigationController.navigationBar.standardAppearance = barApp;
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = OSColor_B;
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *barApp = [UINavigationBarAppearance new];
        barApp.backgroundColor = OSColor_B;
        self.navigationController.navigationBar.scrollEdgeAppearance = barApp;
        self.navigationController.navigationBar.standardAppearance = barApp;
    }
}

-(instancetype)initWithImageUrls:(NSArray *)imageUrls writable:(NSString *)writable
{
    self = [super init];
    if (self) {
        pageNumber = 0;
        if ([writable isEqualToString:@"1"]) {
            [self createNavigationRightFirstTextButtonWith:@"删除" selecteTitle:@"删除"];
        }
        selectIndex = 0;
        _imageArray = (NSMutableArray *)imageUrls;
        self.title = [NSString stringWithFormat:@"1/%ld",_imageArray.count];
        [self setupUI];
    }
    return self;
}

-(instancetype)initWithImageUrls:(NSArray *)imageUrls writable:(NSString *)writable andFirstIndex:(NSInteger)index
{
    self = [super init];
    if (self) {
        pageNumber = index;
        if ([writable isEqualToString:@"1"]) {
            [self createNavigationRightFirstTextButtonWith:@"删除" selecteTitle:@"删除"];
        }
        selectIndex = 0;
        _imageArray = (NSMutableArray *)imageUrls;
        self.title = [NSString stringWithFormat:@"1/%ld",_imageArray.count];
        [self setupUI];
    }
    return self;
}
-(instancetype)initWithImages:(NSArray<UIImage *> *)imageArr withCurrentIndex:(NSInteger)index writable:(NSString *)writable{
    self = [super init];
    if (self) {
        pageNumber = 0;
        selectIndex = index;
        if ([writable isEqualToString:@"1"]) {
            [self createNavigationRightFirstTextButtonWith:@"删除" selecteTitle:@"删除"];
        }
        _imagePictureArr = [[NSMutableArray alloc] initWithArray:imageArr];
        _imageArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < imageArr.count; i++) {
            [_imageArray addObject:imageArr[i]];//占位而已
        }
        self.title = [NSString stringWithFormat:@"1/%ld",_imagePictureArr.count];
        [self setupUI];
        [self scrollToSelectIndex];
    }
    return self;
}
-(instancetype)initWithImages:(NSArray<UIImage *> *)imageArr
{
    self = [super init];
    if (self) {
        pageNumber = 0;
        selectIndex = 0;
        _imagePictureArr = [[NSMutableArray alloc] initWithArray:imageArr];
        _imageArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < imageArr.count; i++) {
            [_imageArray addObject:@""];//占位而已
        }
        self.title = [NSString stringWithFormat:@"1/%ld",_imagePictureArr.count];
        [self setupUI];
    }
    return self;
}
/**
  删除按钮点击事件
 */
- (void)onNavigationRightFirstButtonClicked:(UIButton*)sender
{
    [_imageArray removeObjectAtIndex:selectIndex];
    
    [self.imgScrollView removeFromSuperview];
    selectIndex = 0;
    self.title = [NSString stringWithFormat:@"1/%ld",_imageArray.count];
    [self setupUI];
    //回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(didDeletePhotoImage:)]) {
        [self.delegate didDeletePhotoImage:_imageArray];
    }
    if (_imageArray.count == 0) {
         [self.navigationController popViewControllerAnimated:NO];
       
    }
    
}

-(void)setupUI
{
    self.imgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, KScreenWidth, KScreenHeight-SafeAreaTopHeight)];
    self.imgScrollView.delegate = self;
    self.imgScrollView.backgroundColor = [UIColor blackColor];
    self.imgScrollView.pagingEnabled = YES;
    self.imgScrollView.contentSize = CGSizeMake(KScreenWidth* _imageArray.count, self.imgScrollView.frame.size.height);
    
    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(DeleteSelf)];
    self.imgScrollView.userInteractionEnabled = YES;
    [self.imgScrollView addGestureRecognizer:tap];
    
    self.imgScrollView.contentOffset = CGPointMake(pageNumber*KScreenWidth, self.imgScrollView.contentOffset.y);
    [self.view addSubview:self.imgScrollView];
    
    for (int i=0; i< _imageArray.count; i++) {
        UIImage *image = _imageArray[i];
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-SafeAreaTopHeight)];
        if ([image isKindOfClass:[UIImage class]]) {
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            imageView.image = image;
        }else{
            NSString *imageUrl = [NSString stringWithFormat:@"%@/%@",kFileCacheDirectory,_imageArray[i]];
            //1.先看下本地有没有这个图片
            UIImage *localImage = [UIImage imageWithContentsOfFile:imageUrl];
            if (_imagePictureArr && _imagePictureArr.count>0) {
                localImage = _imagePictureArr[i];
            }
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            if (localImage) {
                [imageView setImage:localImage];
            }
            //2.没有本地图片去网络取
            else{
                imageUrl = kSTRING(_imageArray[i]);
                NSURL *imageUrlNew = [NSURL URLWithString:imageUrl];
                [imageView sd_setImageWithURL:imageUrlNew placeholderImage:[UIImage imageNamed:@"defaultImage"]];
            }
        }
        UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(self.imgScrollView.frame.size.width*i+5, 0, self.imgScrollView.frame.size.width-10, self.imgScrollView.frame.size.height)];
        scrollView.tag = i;
        [self scrollview:scrollView AddScaleImageView:imageView];
        [self.imgScrollView addSubview:scrollView];
    }
}
- (void)scrollToSelectIndex{
    [self.imgScrollView setContentOffset:CGPointMake(KScreenWidth*selectIndex, 0) animated:YES];
}

static const CGFloat MAX_SCALE = 1.0;
-(void)scrollview:(UIScrollView *)scrollView AddScaleImageView:(UIImageView *)scaleImageView
{
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    
    float horizontalScale = scrollView.frame.size.height / scaleImageView.frame.size.height;
    float verticalScale = scrollView.frame.size.width / scaleImageView.frame.size.width;
    float min = MIN(horizontalScale, verticalScale);
    
    float max = MAX(min, MAX_SCALE);//再次比较，万一图片长宽都小于屏幕
    min = MIN(min, MAX_SCALE);//再次判断，万一图片长宽都小于屏幕
    
    scrollView.minimumZoomScale = min;
    scrollView.maximumZoomScale = max;
    scrollView.delegate = self;
    [scrollView addSubview:scaleImageView];
    
    if (max == MAX_SCALE) {
        scaleImageView.transform = CGAffineTransformScale(scaleImageView.transform, min, min);//刚刚出现时缩放成屏幕可以浏览的尺寸
    }
    scaleImageView.center = CGPointMake(scrollView.frame.size.width/2.0, scrollView.frame.size.height/2.0);
}

#pragma  mark UIScrollViewDidScrolldelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if (scrollView != self.imgScrollView) {
        NSInteger i = scrollView.tag;
        UIScrollView * scrollViewZoom = self.imgScrollView.subviews[i];
        UIImageView * scaleImageView = scrollViewZoom.subviews.firstObject;
        return scaleImageView;
    }
    return nil;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offset = scrollView.contentOffset.x;
    selectIndex =  offset/KScreenWidth;
    self.title = [NSString stringWithFormat:@"%ld/%ld",selectIndex+1,_imageArray.count];
    
}
//实现图片在缩放过程中居中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    if (scrollView != self.imgScrollView) {
        
        NSInteger i = scrollView.tag;
        UIScrollView * scrollViewZoom = self.imgScrollView.subviews[i];
        UIImageView * scaleImageView = scrollViewZoom.subviews.firstObject;
        CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?(scrollView.bounds.size.width - scrollView.contentSize.width)/2 : 0.0;
        CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?(scrollView.bounds.size.height - scrollView.contentSize.height)/2 : 0.0;
        
        scaleImageView.center = CGPointMake(scrollView.contentSize.width/2 + offsetX,scrollView.contentSize.height/2 + offsetY);//先定下中心
        
        scrollView.contentSize = CGSizeMake(scrollView.contentSize.width+offsetX, scrollView.contentSize.height+offsetY);//要显示类容的大小
    }
}

-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    //解决事件响应问题(在大scrollView滑动时候禁止内嵌scrollView滑动，否则经常会有无法翻页的bug)
    if (scale<=scrollView.minimumZoomScale) {
        scrollView.scrollEnabled = NO;
    }else{
        scrollView.scrollEnabled = YES;
    }
}

-(void)DeleteSelf{
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

- (void)onNavigationLeftButtonClicked:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:NO];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(SEGShowPhotoViewDelegatePopView)]) {
        [self.delegate SEGShowPhotoViewDelegatePopView];
    }
}
@end
